package com.scrx.ymg.action;

import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.scrx.ymg.entity.AgentDrawings;
import com.scrx.ymg.entity.AgentInfo;
import com.scrx.ymg.entity.DirectInfo;
import com.scrx.ymg.entity.OtherInfo;
import com.scrx.ymg.entity.SuperMarketInfo;
import com.scrx.ymg.service.head.IHeadService;
import com.scrx.ymg.util.BaseUtil;
import com.scrx.ymg.util.HttpUtil;
import com.scrx.ymg.util.PayCommonUtil;
import com.scrx.ymg.util.PayConfigUtil;
import com.scrx.ymg.utilqy.CollectionUtil;
import com.scrx.ymg.utilqy.HttpUtils;
import com.scrx.ymg.utilqy.JsonResult;
import com.scrx.ymg.utilqy.PayUtil;
import com.scrx.ymg.utilqy.ResponseData;
import com.scrx.ymg.utilqy.SerializerFeatureUtil;
import com.scrx.ymg.utilqy.StringUtil;
import com.scrx.ymg.utilqy.WebUtil;
import com.scrx.ymg.utilqy.XmlUtil;
import com.alibaba.fastjson.JSON;


@Controller
@RequestMapping("/transferController")
public class TransferController {

    private static final Logger LOG = Logger.getLogger(TransferController.class);

    private static final String TRANSFERS_PAY = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers"; // 企业付款

    private static final String TRANSFERS_PAY_QUERY = "https://api.mch.weixin.qq.com/mmpaymkttransfers/gettransferinfo"; // 企业付款查询

    private static final String APP_ID = PayConfigUtil.APPID;

    private static final String MCH_ID = PayConfigUtil.MCH_ID;

    private static final String API_SECRET =PayConfigUtil.SECRET;
    
    private static final String callback =PayConfigUtil.call_back;
    
    @Autowired
	private IHeadService heads;

    /**
     * 企业向个人支付转账
     * @param TransferNo
     * @param request
     * @param response
     */
	@ResponseBody
	@RequestMapping(value = "/transferPay", produces = "text/json;charset=UTF-8")
    public void transferPay(String TransferNo,HttpServletRequest request, HttpServletResponse response) {
        LOG.info("[/transfer/pay]");
        //业务判断 openid是否有收款资格
        Map<String, String> restmap = null;
        AgentDrawings drawing=null;
        try {
            drawing = heads.getDrawingsById(TransferNo);
            String optenID=heads.getOpenIdByType(drawing.getMerchantId(),drawing.getTypeId());
            Double amount = drawing.getWithdrawMoney()*100;
            Map<String, String> parm = new HashMap<String, String>();
            parm.put("mch_appid", APP_ID); //公众账号appid
            parm.put("mchid", MCH_ID); //商户号
            parm.put("nonce_str", PayUtil.getNonceStr()); //随机字符串
            parm.put("partner_trade_no", drawing.getId().toString());//商户订单号
            parm.put("openid", optenID); //用户openid
            parm.put("check_name", "FORCE_CHECK"); //校验用户姓名选项 OPTION_CHECK
            parm.put("re_user_name", drawing.getUserName()); //check_name设置为FORCE_CHECK或OPTION_CHECK，则必填
            parm.put("amount", amount.intValue()+""); //转账金额
            parm.put("desc", "乙秒购总部-内部商家转账"); //企业付款描述信息
            parm.put("spbill_create_ip", PayConfigUtil.CREATE_IP); //服务器Ip地址
            parm.put("sign", PayUtil.getSign(parm, PayConfigUtil.API_KEY));
			String restxml = HttpUtils.posts(TRANSFERS_PAY, XmlUtil.xmlFormat(parm, false));
			restmap = XmlUtil.xmlParse(restxml);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }

        if (CollectionUtil.isNotEmpty(restmap) && "SUCCESS".equals(restmap.get("result_code"))) {
            LOG.info("转账成功：" + restmap.get("err_code") + ":" + restmap.get("err_code_des"));
            Map<String, String> transferMap = new HashMap<>();
            transferMap.put("partner_trade_no", restmap.get("partner_trade_no"));//商户转账订单号
            transferMap.put("payment_no", restmap.get("payment_no")); //微信订单号
            transferMap.put("payment_time", restmap.get("payment_time")); //微信支付成功时间
            drawing.setStatus(1);
			drawing.setCheckTime(BaseUtil.newdate());
	    	String  info=heads.updateAgentDrawings(drawing);
	    	if(info=="false"){
	    		 LOG.info("未知错误,企业转账个人成功!!!：但数据库更新状态失败!!!");
	    	}
            WebUtil.response(response,
                    WebUtil.packJsonp(callback,
                            JSON.toJSONString(new JsonResult(1, "转账成功", new ResponseData(null, transferMap)),
                                    SerializerFeatureUtil.FEATURES)));
        }else {
            if (CollectionUtil.isNotEmpty(restmap)) {
                LOG.info("转账失败：" + restmap.get("err_code") + ":" + restmap.get("err_code_des"));
            }
            WebUtil.response(response, WebUtil.packJsonp(callback, JSON
                    .toJSONString(new JsonResult(-1, "转账失败", new ResponseData()), SerializerFeatureUtil.FEATURES)));
        }
    }

    /**
     * 企业向个人转账查询
     * @param request
     * @param response
     * @param tradeno 商户转账订单号
     * @param callback
     */
    @RequestMapping(value = "/pay/query", method = RequestMethod.POST)
    public void orderPayQuery(HttpServletRequest request, HttpServletResponse response, String tradeno,
            String callback) {
        LOG.info("[/transfer/pay/query]");
        if (StringUtil.isEmpty(tradeno)) {
            WebUtil.response(response, WebUtil.packJsonp(callback, JSON
                    .toJSONString(new JsonResult(-1, "转账订单号不能为空", new ResponseData()), SerializerFeatureUtil.FEATURES)));
        }

        Map<String, String> restmap = null;
        try {
            Map<String, String> parm = new HashMap<String, String>();
            parm.put("appid", APP_ID);
            parm.put("mch_id", MCH_ID);
            parm.put("partner_trade_no", tradeno);
            parm.put("nonce_str", PayUtil.getNonceStr());
            parm.put("sign", PayUtil.getSign(parm, API_SECRET));

            String restxml = HttpUtils.posts(TRANSFERS_PAY_QUERY, XmlUtil.xmlFormat(parm, true));
            restmap = XmlUtil.xmlParse(restxml);
        } catch (Exception e) {
            LOG.error(e.getMessage(), e);
        }

        if (CollectionUtil.isNotEmpty(restmap) && "SUCCESS".equals(restmap.get("result_code"))) {
            // 订单查询成功 处理业务逻辑
            LOG.info("订单查询：订单" + restmap.get("partner_trade_no") + "支付成功");
            Map<String, String> transferMap = new HashMap<>();
            transferMap.put("partner_trade_no", restmap.get("partner_trade_no"));//商户转账订单号
            transferMap.put("openid", restmap.get("openid")); //收款微信号
            transferMap.put("payment_amount", restmap.get("payment_amount")); //转账金额
            transferMap.put("transfer_time", restmap.get("transfer_time")); //转账时间
            transferMap.put("desc", restmap.get("desc")); //转账描述
            
            
            WebUtil.response(response, WebUtil.packJsonp(callback, JSON
                    .toJSONString(new JsonResult(1, "订单转账成功", new ResponseData(null, transferMap)), SerializerFeatureUtil.FEATURES)));
        }else {
            if (CollectionUtil.isNotEmpty(restmap)) {
                LOG.info("订单转账失败：" + restmap.get("err_code") + ":" + restmap.get("err_code_des"));
            }
            WebUtil.response(response, WebUtil.packJsonp(callback, JSON
                    .toJSONString(new JsonResult(-1, "订单转账失败", new ResponseData()), SerializerFeatureUtil.FEATURES)));
        }
    }
    
    /**
     * 拒绝提现
     * @return
     */
	@ResponseBody
	@RequestMapping(value = "/rejectTransferPay", produces = "text/json;charset=UTF-8")
    public String rejectTransferPay(String TransferNo){
		AgentDrawings drawing = heads.getDrawingsById(TransferNo);
		return heads.rejectTransferPay(drawing);
    }

}
